package com.gohome.gohomechat.model;

import android.os.Handler;
import android.util.Log;

import com.easemob.chat.EMContactManager;
import com.easemob.exceptions.EaseMobException;
import com.gohome.gohomechat.GoHomeModel;
import com.gohome.gohomechat.db.GoHomeDBTools;
import com.gohome.gohomechat.model.entify.Friend;
import com.gohome.gohomechat.model.modellistener.AddressModelInterface;
import com.gohome.gohomechat.presenter.callback.AddressCallBack;
import com.gohome.gohomechat.utils.ToastUtil;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by dllo on 16/3/1.
 */
public class AddressModel implements AddressModelInterface {
    private List<Friend> datas = new ArrayList<>();
    private Handler handler = new Handler();
    private boolean isRunning;

    @Override
    public synchronized void requestData(final AddressCallBack callBack) {

        handler.post(new Runnable() {
            @Override
            public void run() {
                List<String> usernames = null;//需异步执行
                try {
                    usernames = EMContactManager.getInstance().getContactUserNames();

                    ParseQuery<ParseObject> parseQuery = new ParseQuery("AllUserGoHome");
                    parseQuery.whereContainedIn("username", usernames);
                    final List<String> finalUsernames = usernames;
                    parseQuery.findInBackground(new FindCallback<ParseObject>() {
                        @Override
                        public void done(List<ParseObject> objects, ParseException e) {
                            if (e == null) {
                                for (int i = 0; i < objects.size(); i++) {
                                    ParseFile parseFile = objects.get(i).getParseFile("head_img");
                                    datas.add(new Friend(finalUsernames.get(i), parseFile.getUrl()));
                                    Log.i("wcl", parseFile.getUrl());
                                }
                                Collections.sort(datas); // 升序排列
                                GoHomeModel.getInstance().setIsLoginFirst(false);
                                callBack.onScuess(datas);
                            } else {
                                Log.i("wcl", e.getMessage() + "  lll");
                            }
                        }
                    });

                    ToastUtil.showToast(datas.size() + " ///");
                } catch (EaseMobException e) {
                    Log.i("uiui", e.getMessage() + "失败");
                    callBack.onFailed();
                }

            }
        });
    }

}
